package bb.lanxing.lib.devices.sprint.ymodem;

import android.text.TextUtils;
import bb.lanxing.lib.devices.utils.ByteUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public abstract class YModemInputStream extends InputStream {
    private byte seqNo;
    private int dataSize = 128;
    private byte signal = 1;
    private boolean useBigDataSize = false;

    public abstract String getFileName();

    public abstract long getTotalSize();

    public boolean isUseBigDataSize() {
        return this.useBigDataSize;
    }

    public void setUseBigDataSize(boolean z) {
        this.useBigDataSize = z;
        if (z) {
            this.dataSize = 1024;
            this.signal = (byte) 2;
            return;
        }
        this.dataSize = 128;
        this.signal = (byte) 1;
    }

    protected byte getSeqNo() {
        byte b = this.seqNo;
        this.seqNo = (byte) (b + 1);
        return b;
    }

    public YModem getFirstPacket() {
        long totalSize = getTotalSize();
        String fileName = getFileName();
        if (totalSize <= 0 || TextUtils.isEmpty(fileName)) {
            return null;
        }
        byte[] bArr = new byte[128];
        Arrays.fill(bArr, (byte) 0);
        byte[] stringToBytes = ByteUtils.stringToBytes(fileName + " " + totalSize, "iso-8859-1");
        System.arraycopy(stringToBytes, 0, bArr, 0, stringToBytes.length);
        return YModems.createYModem((byte) 1, getSeqNo(), bArr);
    }

    public YModem readPacket() throws IOException {
        int i = this.dataSize;
        byte[] bArr = new byte[i];
        Arrays.fill(bArr, (byte) 0);
        if (read(bArr, 0, i) == -1) {
            return null;
        }
        return YModems.createYModem(this.signal, getSeqNo(), bArr);
    }

    public byte[] readPacketRaw() throws IOException {
        int i = this.dataSize;
        byte[] bArr = new byte[i];
        Arrays.fill(bArr, (byte) 0);
        if (read(bArr, 0, i) == -1) {
            return null;
        }
        return YModems.createYModemRaw(this.signal, getSeqNo(), bArr);
    }

    @Override
    public synchronized void reset() throws IOException {
        super.reset();
        this.seqNo = (byte) 0;
    }
}
